package com.nbicc.newscat.service.impl;

import com.github.pagehelper.Page;
import com.nbicc.common.Const;
import com.nbicc.common.RequestPageObj;
import com.nbicc.common.ResponseObj;
import com.nbicc.news.po.NewsInfo;
import com.nbicc.newscat.mapper.NewsCatMapper;
import com.nbicc.newscat.po.NewsCat;
import com.nbicc.newscat.service.INewsCatService;
import com.nbicc.parent.serivce.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("NewsCatServiceImpl")
public class NewsCatServiceImpl extends BaseService implements INewsCatService{

    @Autowired
    private NewsCatMapper newsCatMapper;

    @Override
    public Integer insert(NewsCat o) throws Exception {
        return newsCatMapper.insert(o);
    }

    public Integer insertAll(List<NewsCat> newsCats) throws Exception {
        if(newsCats == null || newsCats.size()<1){
            return 0;
        }
        return newsCatMapper.insertAll(newsCats);
    }

    @Override
    public NewsCat selectById(Number id) {
        return null;
    }

    @Override
    public Integer updateById(Object o) throws Exception {
        return null;
    }

    @Override
    public Integer deleteById(Number id) {
        return newsCatMapper.deleteById(id);
    }

    public Integer deleteByMap(Map<String, Object> params) {
        if(params == null){
            return 0;
        }
        if(params.get(NewsCat.FIELD_NEWS_ID) == null
                && params.get(NewsCat.FIELD_CAT_ID) == null ){     //防止删表
            return 0;
        }
        return newsCatMapper.deleteByMap(params);
    }

    @Override
    public ResponseObj find(RequestPageObj<Map<String, Object>> requestPageObj) throws Exception{
        setPageHelper(requestPageObj , NewsInfo.TABLE_NEWS_INFO);
        List<NewsInfo> newsInfos = newsCatMapper.listNewsInfoByCatId(requestPageObj.getData());
        return new ResponseObj(Const.HTTP_STATUS_SUCCESS, newsInfos, ((Page<?>) newsInfos).getTotal());
    }

    @Transactional
    @Override
    public void updateNewsCat(Long newsId, NewsCat[] newsCats) throws Exception {
        Map<String , Object> params = new HashMap<>();
        params.put(NewsCat.FIELD_NEWS_ID , newsId);
        deleteByMap(params);
        List<NewsCat> ncs = Arrays.asList(newsCats);
        ncs.stream().forEach(newsCat -> newsCat.setNewsId(newsId));
        insertAll(ncs);
    }

    @Override
    public long countNews(Map<String, Object> parms) {
        return newsCatMapper.countNews(parms);
    }
}
